package org.jcms.web.filter;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 过滤中文乱码
 * @author 彭功海
 *
 */
@WebFilter("/EncodedFilter")
public class EncodedFilter implements Filter {

	private FilterConfig filterConfig;
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
		String encoding = this.filterConfig.getInitParameter("encoding");
		if(encoding==null||"".equals(encoding)){
			encoding = "UTF-8";
		}
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		resp.setContentType("text/html;charset="+encoding);
		if("get".equalsIgnoreCase(req.getMethod())){
			Map<String, String[]> map = req.getParameterMap();
			Set<String> keys = map.keySet();
			for(String key:keys){
				String[] values = map.get(key);
				for(int i=0;i<values.length;i++){
					values[i] = new String(values[i].getBytes("ISO8859-1"),encoding);
				}
			}
		}
		if("post".equalsIgnoreCase(req.getMethod())){
			req.setCharacterEncoding(encoding);
		}
		chain.doFilter(request, response);
	}
	public void init(FilterConfig filterConfig) throws ServletException {
	 
		this.filterConfig = filterConfig;
	}


	@Override
	public void destroy() {
		filterConfig = null;
		
	}

}
